package com.imhere.sou.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imhere.sou.domain.JsonData;
import com.imhere.sou.domain.PanInfo;
import com.imhere.sou.util.JsonUtil;
import com.imhere.sou.util.StringUtil;

/**
 * 搜索HTTP接口
 * @author 大雄博客
 *
 */
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 8108351916883189933L;
	
	public SearchServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		JsonData jsonData = new JsonData();
		
		String keyword = request.getParameter("keyword");
		Integer page = Integer.valueOf(request.getParameter("page"));
		page = page==null||page<1 ? 1 : page;
		Integer index = (page-1) * 10;
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("现在时间：[" + format.format(new Date()) + "]，搜索关键字：" + keyword + "\n\n");
		
		if(StringUtil.isEmpty(keyword)) {
			jsonData.setErrorMsg("请输入关键字再进行搜索！");
		} else {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			keyword = keyword.trim();
			try {
				
				try {
					keyword = URLEncoder.encode(keyword, "UTF-8");
					String urlStr = "https://www.googleapis.com/customsearch/v1element" +
							"?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1gunmMikTzQqY&rsz=filtered_cse" +
							"&num=10&hl=en&prettyPrint=false&source=gcsc&gss=.com" +
							"&sig=432dd570d1a386253361f581254f9ca1&start=" + index + 
							"&cx=012836602128204570924:t-llpi7axy8&q=" + keyword + "&sort=" +
							"&googlehost=www.google.com&nocache=1458145049928";
					
					dataMap = this.getResult(urlStr, dataMap);
				} catch (Exception e) {
					//异常处理，此处应该做些容错处理
					e.printStackTrace();
				}
				
				dataMap.put("page", page);
				jsonData.setSuccessMsg("获取成功！");
				jsonData.setData(dataMap);
			} catch (Exception e) {
				jsonData.setSuccessMsg("系统暂时不给力，请稍后再试试~~");
				e.printStackTrace();
			}
		}
		
		response.setContentType("application/json;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String json = JsonUtil.bean2Json(jsonData);
		out.write(json);
	}

	public void init() throws ServletException {
		
	}
	
	@SuppressWarnings("unchecked")
	private Map<String, Object> getResult(String urlStr, Map<String, Object> dataMap) throws Exception {
		
		URL url = new URL(urlStr);
	    Long start = System.currentTimeMillis();
		BufferedReader bufr = new BufferedReader(new InputStreamReader(new BufferedInputStream(url.openStream()),"utf-8"));
		System.out.println(System.currentTimeMillis() - start + "ms");
		
		String line = null;
	    StringBuffer sb = new StringBuffer();
	    while((line = bufr.readLine())!=null){
	    	sb.append(line);
	    }
	    System.out.println(System.currentTimeMillis() - start + "ms");
	    bufr.close();
	    
	    String json = sb.toString();
		Map<String, Object> jsonMap = JsonUtil.json2Bean(json, HashMap.class);
	    
		Map<String, Object> pageMap = (HashMap<String, Object>)jsonMap.get("cursor");
	    dataMap.put("index", pageMap.get("currentPageIndex"));
	    dataMap.put("count", pageMap.get("resultCount"));
	    dataMap.put("pages", pageMap.get("pages"));
	    
		List<Map<String, Object>> results = (ArrayList<Map<String,Object>>)jsonMap.get("results");
	    List<PanInfo> infoList = new ArrayList<PanInfo>();
	    
	    Object itemObj = dataMap.get("items");
	    if(itemObj != null) infoList = (ArrayList<PanInfo>) itemObj;
	    
	    for (Map<String, Object> map : results) {
	    	PanInfo panInfo = new PanInfo();
	    	
	    	String title = String.valueOf(map.get("title"));
	    	panInfo.setTitle(title);
	    	
	    	String content = String.valueOf(map.get("content"));
	    	panInfo.setContent(content);
	    	
	    	String linkUrl = String.valueOf(map.get("unescapedUrl"));
	    	panInfo.setLinkUrl(linkUrl);
	    	
	    	String formatUrl = String.valueOf(map.get("formattedUrl"));
	    	panInfo.setFormatUrl(formatUrl);
	    	
	    	infoList.add(panInfo);
		}
	    dataMap.put("items", infoList);
	    
		return dataMap;
	}
}
